//
//  Stack.swift
//  SwiftyDSA
//
//  Created by Archer on 2018/8/4.
//  Copyright © 2018年 Archer. All rights reserved.
//

import Foundation

public final class Stack<Element> {
    
    // a Stack just wrap a Vector
    // which make push/pop done at constant time
    let _storage: Vector<Element>
    
    /// Initialize a Stack through another Stack
    public init(_ other: Stack<Element>) {
        _storage = Vector(other._storage)
    }
    
    /// Initialize a empty Stack with capacity you specialfied
    public init(capacity: Int = kVectorDefaultCapacity) {
        _storage = Vector(capacity: capacity)
    }
    
    /// Indicates number of elements in Stack
    public var count: Int { return _storage.count }
    /// whether the Stack is empty
    public var isEmpty: Bool { return _storage.isEmpty }
    
    /// 读栈顶元素
    public var top: Element? { return _storage.last }
    
    /// 入栈
    public func push(_ element: Element) {
        _storage.insert(element)
    }
    
    /// 出栈
    public func pop() -> Element? {
        return _storage.removeLast()
    }
}

/// FIXME: Element should confirms to Cloneable to make a deep copy
extension Stack: Cloneable {
    public func clone() -> Stack {
        return Stack(self) 
    }
}

/// 数组字面量初始化
extension Stack: ExpressibleByArrayLiteral {
    public convenience init(arrayLiteral elements: Element...) {
        self.init(capacity: elements.count * 2)
        elements.forEach { _storage.insert($0) }
    }
}
